package q640_solveEquation;

public class Solution {
    /*
    直接模拟两侧的运算即可 因为没有括号和乘除 所以分别维护左右两侧x的数量 和 左右两侧数字和 四个变量
    最后统一到左侧 即可得到答案
     */
    public String solveEquation(String equation) {
        String[] functions = equation.split("=");
        int leftX = 0, rightX = 0;
        int leftVal = 0, rightVal = 0;
        boolean sign = true;
        for (int i = 0; i < functions[0].length(); ) {
            if (functions[0].charAt(i) == 'x') {
                leftX += sign ? 1 : -1;
                ++i;
            } else if (functions[0].charAt(i) == '+') {
                sign = true;
                ++i;
            } else if (functions[0].charAt(i) == '-') {
                sign = false;
                ++i;
            } else {
                int temp = 0;
                while (i < functions[0].length() && Character.isDigit(functions[0].charAt(i))) {
                    temp = temp * 10 + functions[0].charAt(i) - '0';
                    ++i;
                }
                if (i < functions[0].length() && functions[0].charAt(i) == 'x') {
                    leftX += sign ? temp : -temp;
                    ++i;
                } else if (sign) {
                    leftVal += temp;
                } else {
                    leftVal -= temp;
                }
            }
        }
        sign = true;
        for (int i = 0; i < functions[1].length(); ) {
            if (functions[1].charAt(i) == 'x') {
                rightX += sign ? 1 : -1;
                ++i;
            } else if (functions[1].charAt(i) == '+') {
                sign = true;
                ++i;
            } else if (functions[1].charAt(i) == '-') {
                sign = false;
                ++i;
            } else {
                int temp = 0;
                while (i < functions[1].length() && Character.isDigit(functions[1].charAt(i))) {
                    temp = temp * 10 + functions[1].charAt(i) - '0';
                    ++i;
                }
                if (i < functions[1].length() && functions[1].charAt(i) == 'x') {
                    rightX += sign ? temp : -temp;
                    ++i;
                } else if (sign) {
                    rightVal += temp;
                } else {
                    rightVal -= temp;
                }
            }
        }
        int Num_x = leftX - rightX, Num_Val = rightVal - leftVal;
        if (Num_x == 0 && Num_Val == 0) return "Infinite solutions";
        if (Num_x == 0) return "No solution";

        return "x=" + Num_Val/Num_x;
    }
}
